﻿@page "/Admin/PluginManager"
@using JxAudio.Plugin
@using System.Diagnostics.CodeAnalysis
@using System.IO.Compression
@using Microsoft.Extensions.Localization
@using Constants = JxAudio.Core.Constants

@inject IStringLocalizer<PluginManager> PluginManagerLocalizer
@inject IDispatchService<string> DispatchService
@inject SwalService SwalService
@inject ToastService ToastService

<AdminTable TItem="PluginConfig" Items="PluginConfigs" ShowToolbar="true" ShowDefaultButtons="false" 
            ShowExtendButtons="true" ShowExtendEditButton="false" ShowExtendDeleteButton="false" ShowSearch="false">
    <TableColumns>
        <TableColumn @bind-Field="@context.Id"></TableColumn>
        <TableColumn @bind-Field="@context.Name"></TableColumn>
        <TableColumn @bind-Field="@context.Author"></TableColumn>
        <TableColumn @bind-Field="@context.Description" TextEllipsis="true"></TableColumn>
        <TableColumn @bind-Field="@context.Version"></TableColumn>
        <TableColumn @bind-Field="@context.IsEnable"></TableColumn>
    </TableColumns>
    <RowButtonTemplate>
        <TableCellButton Text="@(context.IsEnable ? PluginManagerLocalizer["Disable"] : PluginManagerLocalizer["Enable"])"
                         OnClick="() => ChangeStatus(context)"></TableCellButton>
    </RowButtonTemplate>
    <TableToolbarTemplate>
        <TableToolbarComponent>
            <ButtonUpload TValue="string" BrowserButtonText="@PluginManagerLocalizer["Upload"]" OnChange="Upload"></ButtonUpload>
        </TableToolbarComponent>
    </TableToolbarTemplate>
</AdminTable>

@code {
    [NotNull]
    private List<PluginConfig>? PluginConfigs { get; set; }

    protected override void OnInitialized()
    {
        base.OnInitialized();
        PluginConfigs = PluginUtil.GetAllPlugins();
    }

    private void ChangeStatus(PluginConfig pluginConfig)
    {
        if (PluginUtil.ChangePluginStatus(pluginConfig.Id!, out var isEnable))
        {
            pluginConfig.IsEnable = isEnable;
            DispatchService.Dispatch(new DispatchEntry<string>()
            {
                Name = "menu",
                Entry = "plugin"
            });
        }
    }

    private async Task Upload(UploadFile uploadFile)
    {
        if (uploadFile.GetExtension() != ".jxaudio" || uploadFile.File is null || uploadFile.OriginFileName is null)
        {
            await SwalService.Show(new SwalOption()
            {
                Title = PluginManagerLocalizer["Error"],
                Content = PluginManagerLocalizer["OnlySupportJxAudioFile"],
                Category = SwalCategory.Error
            });
            return;
        }
        var pluginPath = Path.Combine(AppContext.BaseDirectory, Constants.PluginPath);
        var pluginName = Path.GetFileNameWithoutExtension(uploadFile.OriginFileName);
        if (Directory.Exists(Path.Combine(pluginPath, pluginName)))
        {
            var plugin = PluginConfigs.FirstOrDefault(x => x.Id == pluginName);
            if (plugin is { IsEnable: true })
            {
                await SwalService.Show(new SwalOption()
                {
                    Title = PluginManagerLocalizer["Error"],
                    Content = PluginManagerLocalizer["EnableCannotReplace"],
                    Category = SwalCategory.Error
                });
                return;
            }
            
            if (!await SwalService.ShowModal(new SwalOption()
                {
                    Title = PluginManagerLocalizer["Question"],
                    Content = PluginManagerLocalizer["PluginAlreadyExists"],
                    Category = SwalCategory.Question
                }))
            {
                return;
            }
            
        }

        var stream = uploadFile.File.OpenReadStream();
        var memoryStream = new MemoryStream();
        await stream.CopyToAsync(memoryStream);
        memoryStream.Seek(0, SeekOrigin.Begin);

        ZipFile.ExtractToDirectory(memoryStream, Constants.PluginPath, true);
        await ToastService.Show(new ToastOption()
        {
            Title = PluginManagerLocalizer["Success"],
            Content = PluginManagerLocalizer["UploadSuccess"],
            Category = ToastCategory.Success
        });
        PluginConfigs = PluginUtil.GetAllPlugins();
        await InvokeAsync(StateHasChanged);
    }

}